///package servlet1;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import service.AirlineReservationServiceProxy;
import bean.Flight;
import constants.AirlineReservationServiceConstants;

/**
 * Servlet implementation class SearchFlightsServlet
 */
public class SearchFlightsServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

    /**
     * Default constructor. 
     */
    public SearchFlightsServlet() {
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		AirlineReservationServiceProxy proxy = new AirlineReservationServiceProxy(
				AirlineReservationServiceConstants.SERVICE_URL);
		
		String source = request.getParameter("origin");
		String destination = request.getParameter("destination");
		String startDate = request.getParameter("startDate");
		String returnDate = request.getParameter("returnDate");
		String tripType = request.getParameter("tripType");
		int numTravelers = Integer.parseInt(request.getParameter("numTravelers"));
				
		Flight[] flights = proxy.searchFlights(source, destination, startDate, returnDate, tripType, numTravelers);
		List<Flight> oneWayTripFlights = new ArrayList<Flight>();
		List<Flight> returnTripFlights = new ArrayList<Flight>();
		
		if(flights != null){
			List<Flight> lstFlights = Arrays.asList(flights);
			System.out.println("Helooooooooodsdsfdsoooooo" + lstFlights.size());
			
			
			for(Flight f: lstFlights){
				if(f.getSource().equalsIgnoreCase(source) || f.getIntermediate().equalsIgnoreCase(source)){
					oneWayTripFlights.add(f);
				}else
				if(f.getSource().equalsIgnoreCase(destination) || f.getIntermediate().equalsIgnoreCase(destination)){
					returnTripFlights.add(f);
				}
			}
		}
		
		
		HttpSession session = request.getSession();
		
		//System.out.println("----------"+ lstFlights.size());
		session.setAttribute("oneWayTripFlights", oneWayTripFlights);
		session.setAttribute("returnTripFlights", returnTripFlights);
		
			request.getRequestDispatcher("customer/flights.jsp").include(request, response);
	}

}
